<template>
  <div class="chat-container">
    <div class="chat-history">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div class="message-content" v-html="renderMarkdown(message.content)"></div>
      </div>
    </div>
    <div class="chat-input">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="Type your message..." />
      <button @click="sendMessage">Send</button>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

export default {
  data() {
    return {
      userInput: '',
      messages: [],
    };
  },
  methods: {
    sendMessage() {
      if (!this.userInput.trim()) return;

      const userMessage = {role: 'user', content: this.userInput};
      this.messages.push(userMessage);

      const aiMessage = {role: 'assistant', content: ''};
      this.messages.push(aiMessage);

      this.userInput = '';

      // 使用 EventSource 接收 SSE 流
      const eventSource = new EventSource(
          `http://localhost:8080/deepseek/ai/generateStream?message=${encodeURIComponent(
              userMessage.content
          )}`
      );

      eventSource.onmessage = (event) => {
        aiMessage.content += event.data; // 追加流式数据
        this.$forceUpdate(); // 强制更新视图
      };

      eventSource.onerror = () => {
        eventSource.close(); // 关闭连接
        aiMessage.content += '\n\n[Stream ended]'; // 标记流结束
        this.$forceUpdate();
      };
    },
    renderMarkdown(content) {
      marked.setOptions({
        highlight: function (code, lang) {
          const language = hljs.getLanguage(lang) ? lang : 'plaintext';
          return hljs.highlight(code, {language}).value;
        },
      });
      return marked(content);
    },
  },
};
</script>

<style>
/* 样式保持不变 */
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.chat-history {
  border: 1px solid #ccc;
  padding: 10px;
  height: 500px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 10px;
}

.message.user {
  text-align: right;
}

.message.assistant {
  text-align: left;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f1f1f1;
}

.chat-input {
  display: flex;
}

.chat-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.chat-input button {
  margin-left: 10px;
  padding: 8px 16px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #0056b3;
}
</style>
